package com.andova.component.lbs;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.andova.component.AndovaComponentManager;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import androidx.annotation.Nullable;

/**
 * Created by Administrator on 2017-12-06.
 *
 * @author kzaxil
 * @since 1.0.1
 */
public class BaiDuLocService extends Service implements BDLocationListener {
    private LocationClient mLocClient;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initOption();
        mLocClient.registerLocationListener(this);
        mLocClient.start();
    }

    private void initOption() {
        boolean isInit;
        try {
            mLocClient = new LocationClient(this,
                    (LocationClientOption) AndovaComponentManager.getInstance().lbsComponent().lbsLocOption().locOption());
            isInit = true;
        } catch (NullPointerException | ClassCastException e) {
            Log.i(getClass().getSimpleName(), "use default location option of lbs!");
            isInit = false;
        }
        if (isInit) return;
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setScanSpan(60000);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("gcj02");
        mLocClient = new LocationClient(this, option);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        try {
            AndovaComponentManager.getInstance().lbsComponent().lbsLocInfo().locInfo(bdLocation);
        } catch (NullPointerException e) {
            e.printStackTrace();
            stopSelf();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocClient.isStarted()) mLocClient.stop();
        mLocClient.unRegisterLocationListener(this);
    }
}
